package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CategoryService categoryService;
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        Page<Category> categoryPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.orderByAsc(Category::getSort);
        categoryService.page(categoryPage,qw);
        return R.success(categoryPage);

    }
    @PostMapping
    public R<String> addCategory(@RequestBody Category category){
        categoryService.save(category);
        redisTemplate.delete("category");
        return R.success("添加成功");
    }
    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        redisTemplate.delete("category");
        return R.success("修改成功");
    }
    @DeleteMapping
    public R<String> deleteById(long id){
        categoryService.remove(id);
        redisTemplate.delete("category");
        return R.success("删除成功");
    }
    @GetMapping("/list")
    public R<List<Category>> list(Integer type){
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(StringUtils.checkValNotNull(type),Category::getType,type);
        List<Category> list =redisTemplate.opsForList().range("category",0,-1);//取全部数据
        if (list==null||list.size()==0){
            list = categoryService.list(qw);
            redisTemplate.opsForList().rightPushAll("category",list);
        }
        return R.success(list);
    }
}
